using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace Baula.TextGen.ActiveTemplating
{
    public interface IFormsContext : IEnumerable<IFormInfo>
    {
        void Add(IFormInfo form);
        int Count { get; }
        IFormInfo this[int index] { get; }
        IFormInfo this[string formName] { get; }
    }

    public class FormsContext : IFormsContext
    {
        private readonly IList<IFormInfo> _forms;

        public FormsContext()
        {
            _forms = new List<IFormInfo>();
        }

        public FormsContext(IEnumerable<FormInfo> formInfos)
        {
            _forms = new List<IFormInfo>(formInfos);
        }

        public void Add(IFormInfo form)
        {
            _forms.Add(form);
        }

        public virtual int Count
        {
            get { return _forms.Count; }
        }

        public virtual IEnumerator<IFormInfo> GetEnumerator()
        {
            return _forms.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public virtual IFormInfo this[int index]
        {
            get { return _forms[index]; }
        }

        public virtual IFormInfo this[string formName]
        {
            get
            {
                var firstOrDefault = _forms.FirstOrDefault(form => form.Name == formName);
                if (firstOrDefault == null)
                    throw new IndexOutOfRangeException(string.Format("There is no form with name \"{0}\".", formName));
                return firstOrDefault;
            }
        }
    }
}